package app;

import java.util.*;

import com.StarMicronics.StarIOSDK.R;

import utils.*;

import android.content.Context;
import android.graphics.*;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.view.View.*;
import android.widget.*;

public class TicketView implements NotificationListener {
	public View ticketView;
	public ImageView ticketBGView;
	public ImageView logo;
	public TextView add_water_by;
	public TextView add_water_gal;
	public FrameLayout time_left_plant_layout;
	public FrameLayout time_arrived_job_layout;
	public FrameLayout time_start_pour_layout;
	public FrameLayout time_finished_pour_layout;
	public FrameLayout time_left_job_layout;
	public FrameLayout time_arrived_plant_layout;
	public TextView time_left_plant;
	public TextView time_arrived_job;
	public TextView time_start_pour;
	public TextView time_finished_pour;
	public TextView time_left_job;
	public TextView time_arrived_plant;
	public TextView time_elapsed;
	public TextView date;
	public TextView trunk_no;
	public TextView driver;
	public TextView slump;
	public TextView plant_code;
	public TextView ticker_number;
	public TextView job_no;
	public TextView PO_no;
	public TextView account_no;
	public TextView project_no;
	public TextView address;
	public TextView sold_to;
	public ListView table;
	private MyAdapter adapter;
	public TextView remarks;
	public TextView total_ordered;
	public TextView yards_today;
	public TextView allowable_time;
	public TextView sub_total;
	public TextView red_by;
	public TextView collect_grand_total;
	public TextView tax;
	public TextView total;
	public Button batch_weight;
	public TextView slip_no;
	public ImageView accpet;
	public TextView note;
	public ImageView sign;
	
	public MapView map;
	//public UIScrollView scroll;
	
	public TicketView() {
		loadXmlView();
		AppDelegate.sharedInstance().addNotificationListener(DataSourceChangeNotificationListener.class, this);
		AppDelegate.sharedInstance().addNotificationListener(ImageDownloaderNotificationListener.class, this);
	}
	
	public void dealloc() {
		map.dealloc();
		timer.cancel();
		timer = null;
		AppDelegate.sharedInstance().removeNotificationListener(DataSourceChangeNotificationListener.class, this);
		AppDelegate.sharedInstance().removeNotificationListener(ImageDownloaderNotificationListener.class, this);
	}
	
	private void modify() {
		new AddWaterView(ticketID);
	}
	
	private void accept() {
	}
	
	private void showBatchWeight() {
		Dictionary<String, Object> c = AppDelegate.sharedInstance().getMain().ticketsDataSource.memoryObject.get(Long.valueOf(ticketID));
		if (c != null) {
			String txt = (String) c.get(TicketList.BATCH_WEIGHT);
			if (txt != null || c.get(TicketList.HIDE_BATCH_WEIGHT) != null) {
				new DetailInformation(txt);
			}
		}
	}
	
	private void showRemark() {
		new DetailInformation((String)remarks.getText());
	}
	
	private void showNote() {
		new DetailInformation((String)note.getText());
	}
	
	
	private long ticketID;
	public long getTicketId() {
		return ticketID;
	}
	private void _dataSourceChanged() {
		TicketList list = AppDelegate.sharedInstance().getMain().ticketsDataSource;
		Vector<Dictionary<String, Object>> arr = list.data;
		Dictionary<String, Object> dic = null;
		for (int i = 0; i < arr.size(); i++) {
			Dictionary<String, Object> ticket = arr.elementAt(i);
			if (IntConvert.parseLong(ticket.get("TicketID")) == ticketID) {
				dic = ticket;
			}
		}
		
		if (dic == null) {
			adapter.products = null;
			adapter.notifyDataSetInvalidated();

			
			date.setText(null);
			trunk_no.setText(null);
			slump.setText(null);
			plant_code.setText(null);
			ticker_number.setText(null);
			PO_no.setText(null);
			account_no.setText(null);

			address.setText(null);

		    sold_to.setText(null);

		    remarks.setText(null);

		    total_ordered.setText(null);
		    yards_today.setText(null);
		    allowable_time.setText(null);
		
		    map.setMapWithPlat(null, null);
		    add_water_by.setText(null);
		    add_water_gal.setText(null);
		    
		    time_left_plant.setText(null);
		    time_arrived_job.setText(null);
		    time_start_pour.setText(null);
		    time_finished_pour.setText(null);
		    time_left_job.setText(null);
		    time_arrived_plant.setText(null);
		    time_elapsed.setText(null);
	    	accpet.setImageDrawable(view.getResources().getDrawable(R.drawable.uncheck));
		    note.setText(null);

	    	batch_weight.setText(null);

		    logo.setImageBitmap(null);
		    
	    	sign.setImageBitmap(null);
		} else {
			adapter.products = (Vector<Dictionary<String, String>>) dic.get("Products");
			adapter.notifyDataSetInvalidated();
			
			date.setText((String) dic.get("Date"));
			trunk_no.setText((String) dic.get("Truck_"));
			slump.setText((String) dic.get("Slump"));
			plant_code.setText((String) dic.get("PlantID"));
			ticker_number.setText((String) dic.get("Ticket_"));
			PO_no.setText((String) dic.get("PurchaseOrderNum"));
			account_no.setText((String) dic.get("CustomerID"));
			
			String address1 = (String) dic.get("DeliveryAddress1");
			String address2 = (String) dic.get("DeliveryAddress2");
			if (address1 == null) address1 = "";
			if (address2 == null) address2 = "";
			address.setText(address1+"\n"+address2);
			
			
//			String Shiptocustomeraddress1 = (String)dic.get("Shiptocustomeraddress1");
//			String Shiptocustomercity = (String)dic.get("Shiptocustomercity");
//			String Shiptocustomercod = (String)dic.get("Shiptocustomercod");
//		    String Shiptocustomername = (String)dic.get("Shiptocustomername");
//		    String Shiptocustomerpostalcd = (String)dic.get("Shiptocustomerpostalcd");
//		    if (Shiptocustomeraddress1 == null) Shiptocustomeraddress1 = "";
//		    if (Shiptocustomercity == null) Shiptocustomercity = "";
//		    if (Shiptocustomercod == null) Shiptocustomercod = "";
//		    if (Shiptocustomername == null) Shiptocustomername = "";
//		    if (Shiptocustomerpostalcd == null) Shiptocustomerpostalcd = "";
//
//		    sold_to.setText(Shiptocustomeraddress1+"\n"+Shiptocustomercity+"\n"+Shiptocustomercod+"\n"+Shiptocustomername+"\n"+Shiptocustomerpostalcd);

			String CustomerName_1 = (String) dic.get("CustomerName_1");
			String CustomerName_2 = (String) dic.get("CustomerName_2");
		    String CustomerName_3 = (String) dic.get("CustomerName_3");
		    if (CustomerName_1 == null) CustomerName_1 = "";
		    if (CustomerName_2 == null) CustomerName_2 = "";
		    if (CustomerName_3 == null) CustomerName_3 = "";
		    
		    sold_to.setText(CustomerName_1+"\n"+CustomerName_2+"\n"+CustomerName_3);
		    
		    StringBuffer temp = new StringBuffer();
		    String instruct = (String) dic.get("DeliveryInstructions1");
		    if (instruct != null && instruct.length() > 0) {
		    	if (temp.length() > 0) {
		    		temp.append('\n');
		    	}
		    	temp.append(instruct);
		    }
		    instruct = (String) dic.get("DeliveryInstructions2");
		    if (instruct != null && instruct.length() > 0) {
		    	if (temp.length() > 0) {
		    		temp.append('\n');
		    	}
		    	temp.append(instruct);
		    }
		    instruct = (String) dic.get("DeliveryInstructions3");
		    if (instruct != null && instruct.length() > 0) {
		    	if (temp.length() > 0) {
		    		temp.append('\n');
		    	}
		    	temp.append(instruct);
		    }
		    remarks.setText(temp.toString());

		    total_ordered.setText((String)dic.get("OrderedQuantity"));
		    yards_today.setText((String)dic.get("CumulativeQuantity"));
		    allowable_time.setText((String)dic.get("TimeDueonJob"));
		    if (dic.get("Subtotal") != null) sub_total.setText(IntConvert.to2fString((String) dic.get("Subtotal")));
		    if (dic.get("Tax") != null) tax.setText(IntConvert.to2fString((String) dic.get("Tax")));
		    if (dic.get("Total") != null) total.setText(IntConvert.to2fString((String) dic.get("Total")));
		
		    Dictionary<String, Object> custom = list.memoryObject.get(Long.valueOf(ticketID));
		    map.setMapWithPlat((String)dic.get("chj_address"), (String)custom.get(TicketList.PLANT_ADDR));
		    add_water_by.setText((String)custom.get(TicketList.SIGN_NAME));
		    add_water_gal.setText((String)custom.get(TicketList.ADD_WATER_GAL));
		    
		    time_left_plant.setText((String)custom.get(TicketList.STR_TIME_LEFT_PLANT));
		    time_arrived_job.setText((String)custom.get(TicketList.STR_TIME_ARRIVED_JOB));
		    time_start_pour.setText((String)custom.get(TicketList.STR_TIME_START_POUR));
		    time_finished_pour.setText((String)custom.get(TicketList.STR_TIME_FINISHED_POUR));
		    time_left_job.setText((String)custom.get(TicketList.STR_TIME_LEFT_JOB));
		    time_arrived_plant.setText((String)custom.get(TicketList.STR_TIME_ARRIVED_PLANT));
		    time_elapsed.setText((String)custom.get(TicketList.STR_TIME_ELAPSED));
		    if (IntConvert.parseInt(custom.get(TicketList.ACCEPT_TERMS)) == 1) {
		    	accpet.setImageDrawable(view.getResources().getDrawable(R.drawable.check));
		    } else {
		    	accpet.setImageDrawable(view.getResources().getDrawable(R.drawable.uncheck));
		    }
		    note.setText((String)custom.get(TicketList.DRIVER_NOTE));

		    if (custom.get(TicketList.BATCH_WEIGHT) != null && IntConvert.parseInt(custom.get(TicketList.HIDE_BATCH_WEIGHT)) == 0) {
		    	batch_weight.setText(FilePack.getStringByID(STRING_ID.STR_BATCH_WEIGHT));
		    } else {
		    	batch_weight.setText("");
		    }

		    logo.setImageBitmap(ImageDownloader.sharedInstance().downloadImage((String)custom.get(TicketList.LOGO_URL)));
		    
		    Vector<Bitmap> temp_arr = (Vector<Bitmap>)custom.get(TicketList.SIGNATURE);
		    if (temp_arr != null && temp_arr.size() > 0) {
		    	sign.setImageBitmap(temp_arr.elementAt(0));
		    } else {
		    	sign.setImageBitmap(null);
		    }
		}
	}
	
	public void notification(Class<?> clss, Object object, Object notification) {
		if (clss == DataSourceChangeNotificationListener.class) {
			TicketList list = AppDelegate.sharedInstance().getMain().ticketsDataSource;
			if (object == list) {
				Dictionary<String, Vector<Long>> userInfo = (Dictionary<String, Vector<Long>>)notification;
				Vector<Long> changed = userInfo.get("changed");
				if (changed.indexOf(Long.valueOf(ticketID)) != -1) {
					_dataSourceChanged();
				}
			}
		} else if (clss == ImageDownloaderNotificationListener.class) {
			TicketList list = AppDelegate.sharedInstance().getMain().ticketsDataSource;
			Dictionary<String, Object> custom = list.memoryObject.get(Long.valueOf(ticketID));
			
			if (custom.get(TicketList.LOGO_URL) != null && custom.get(TicketList.LOGO_URL).equals(notification)) {
				logo.setImageBitmap(ImageDownloader.sharedInstance().downloadImage((String)notification));
			}
		}
	}
	
	public void setTicketId(long _ticketID) {
		if (ticketID != _ticketID) {
			ticketID = _ticketID;
			_dataSourceChanged();
		}
	}

	
	
	
	
	private final class ViewHolder {  
        private TextView productNo;
        private TextView description;
        private TextView unit;
        private TextView quantity;
        private TextView price;
        private TextView amount;
    }

	
	private final class MyAdapter extends BaseAdapter {  
        private LayoutInflater mInflater;
        private Vector<Dictionary<String, String>> products;
        public MyAdapter(Context context) {  
            this.mInflater = LayoutInflater.from(context);  
        }  
        public int getCount() {  
        	if (products == null) {
        		return 0;
        	} else {
        		return products.size();
        	}
        }  
        public Object getItem(int arg0) {  
            return products.elementAt(arg0);  
        }  
        public long getItemId(int arg0) {  
            return arg0;  
        }  
        public View getView(int position, View convertView, ViewGroup parent) {  
            ViewHolder holder = null;  
            if (convertView == null) {  
                holder = new ViewHolder();  
                convertView = mInflater.inflate(R.layout.product_cell, null);  
                holder.productNo = (TextView) convertView.findViewById(R.id.product_no);  
                holder.description = (TextView) convertView.findViewById(R.id.description);  
                holder.unit = (TextView) convertView.findViewById(R.id.unit);  
                holder.quantity = (TextView) convertView.findViewById(R.id.quantity);  
                holder.price = (TextView) convertView.findViewById(R.id.price);  
                holder.amount = (TextView) convertView.findViewById(R.id.amount);  

                convertView.setTag(holder);
            } else {  
                holder = (ViewHolder) convertView.getTag();  
            }
            
            Dictionary<String, String> dic = products.elementAt(position);
            holder.productNo.setText(dic.get("Productno"));
            holder.description.setText(dic.get("description"));
            holder.unit.setText(dic.get("unit"));
            holder.quantity.setText(dic.get("quantity"));
            holder.price.setText(IntConvert.to2fString(dic.get("unitprice")));
            holder.amount.setText(IntConvert.to2fString(dic.get("amount")));
            return convertView;  
        }
    }
	
	
	
	public View view;
	private Button button_accept;
	private Button button_modify;
	private Button button_show_remark;
	private Button button_show_note;
	public View mapLayout;
	public View ticketLayout;
	private void loadXmlView() {
        view = AppDelegate.sharedInstance().activity.getLayoutInflater().inflate(R.layout.ticket, null);
		ticketView = view.findViewById(R.id.ticket_view);
		ticketBGView = (ImageView) view.findViewById(R.id.ticketBGView);
		logo = (ImageView)view.findViewById(R.id.logo);
		add_water_by = (TextView) view.findViewById(R.id.add_water_by);
		add_water_gal = (TextView) view.findViewById(R.id.add_water_gal);
		date = (TextView) view.findViewById(R.id.date);
		trunk_no = (TextView) view.findViewById(R.id.trunk_no);
		driver = (TextView) view.findViewById(R.id.driver);
		slump = (TextView) view.findViewById(R.id.slump);
		plant_code = (TextView) view.findViewById(R.id.plant_code);
		ticker_number = (TextView) view.findViewById(R.id.ticker_number);
		time_left_plant = (TextView) view.findViewById(R.id.time_left_plant);
		time_arrived_job = (TextView) view.findViewById(R.id.time_arrived_job);
		time_start_pour = (TextView) view.findViewById(R.id.time_start_pour);
		time_finished_pour = (TextView) view.findViewById(R.id.time_finished_pour);
		time_left_job = (TextView) view.findViewById(R.id.time_left_job);
		time_arrived_plant = (TextView) view.findViewById(R.id.time_arrived_plant);
		time_left_plant_layout = (FrameLayout) view.findViewById(R.id.time_left_plant_layout);
		time_arrived_job_layout = (FrameLayout) view.findViewById(R.id.time_arrived_job_layout);
		time_start_pour_layout = (FrameLayout) view.findViewById(R.id.time_start_pour_layout);
		time_finished_pour_layout = (FrameLayout) view.findViewById(R.id.time_finished_pour_layout);
		time_left_job_layout = (FrameLayout) view.findViewById(R.id.time_left_job_layout);
		time_arrived_plant_layout = (FrameLayout) view.findViewById(R.id.time_arrived_plant_layout);
		time_elapsed = (TextView) view.findViewById(R.id.time_elapsed);
		address = (TextView) view.findViewById(R.id.address);
		sold_to = (TextView) view.findViewById(R.id.sold_to);
		job_no = (TextView) view.findViewById(R.id.job_no);
		PO_no = (TextView) view.findViewById(R.id.PO_no);
		account_no = (TextView) view.findViewById(R.id.account_no);
		project_no = (TextView) view.findViewById(R.id.project_no);
		table = (ListView) view.findViewById(R.id.table);
		remarks = (TextView) view.findViewById(R.id.remarks);
		total_ordered = (TextView) view.findViewById(R.id.total_ordered);
		yards_today = (TextView) view.findViewById(R.id.yards_today);
		allowable_time = (TextView) view.findViewById(R.id.allowable_time);
		sub_total = (TextView) view.findViewById(R.id.sub_total);
		tax = (TextView) view.findViewById(R.id.tax);
		total = (TextView) view.findViewById(R.id.total);
		red_by = (TextView) view.findViewById(R.id.red_by);
		collect_grand_total = (TextView) view.findViewById(R.id.collect_grand_total);
		batch_weight = (Button) view.findViewById(R.id.batch_weight);
		accpet = (ImageView) view.findViewById(R.id.accpet);
		button_accept = (Button) view.findViewById(R.id.button_accept);
		slip_no = (TextView) view.findViewById(R.id.slip_no);
		button_modify = (Button) view.findViewById(R.id.button_modify);
		note = (TextView) view.findViewById(R.id.note);
		button_show_remark = (Button) view.findViewById(R.id.button_show_remark);
		button_show_note = (Button) view.findViewById(R.id.button_show_note);
		sign = (ImageView) view.findViewById(R.id.sign);
		ticketLayout = view.findViewById(R.id.ticket_layout);
		mapLayout = view.findViewById(R.id.map_layout);
		map = new MapView((RelativeLayout)mapLayout);
		
		batch_weight.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showBatchWeight();
			}
		});
		button_accept.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				accept();
			}
		});
		button_modify.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				modify();
			}
		});
		button_show_remark.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showRemark();
			}
		});
		button_show_note.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showNote();
			}
		});
		
		
		adapter = new MyAdapter(AppDelegate.sharedInstance().activity);
		table.setAdapter(adapter);
		
		timer.schedule(task, 1000, 1000);
		timeSecond();
	}
	
	
	private void timeSecond() {
		if (trunk_no.getVisibility() == View.VISIBLE) {
			trunk_no.setVisibility(View.INVISIBLE);
		} else {
			trunk_no.setVisibility(View.VISIBLE);
		}
	}
	
	Timer timer = new Timer();  
    Handler handler = new Handler(){  
  
        public void handleMessage(Message msg) {  
        	timeSecond();
            super.handleMessage(msg);  
        }  
          
    };  
    TimerTask task = new TimerTask(){  
  
        public void run() {
            Message message = new Message();      
            message.what = 1;
            handler.sendMessage(message);    
        }
    };  
}
